import React from 'react'
import { Table, Icon, Modal, Popconfirm, Message, Form, Row, Select, Col, Button, Input, DatePicker } from 'antd';
const FormItem = Form.Item;
import apiAgentType from '../../../api/agentType';
import apiRole from '../../../api/role';

import PanelBox from '../../../components/PanelBox';
import AgentTypeForm from '../../Form/AgentType';
import { jsonToTree, jsonToTreeByRoot } from "../../../utils/tools";
const { RangePicker } = DatePicker;

export default class TablePage extends React.Component {
  columns = [{
    title: '代理商类型名称',
    key: 'name',
    dataIndex: 'name',
    sorter: true,
    width: '20%',
  }, {
    title: '代理商描述',
    key: 'descr',
    dataIndex: 'descr',
    width: '20%',
  }, {
    title: '排序号',
    key: 'sort',
    dataIndex: 'sort',
  }, {
    title: '创建时间',
    key: 'createDate',
    dataIndex: 'createDate',
  }, {
    title: '操作',
    key: 'id',
    dataIndex: 'id',
    render: (text, record) => (
      <span>
        <a href="javascript:void(0)" onClick={() => this.startUpdate(record)} >编辑</a>
        <span className="ant-divider" />
        <Popconfirm title="您是否要删除跟用户?" onConfirm={() => this.handleLogOut(text)} okText="是" cancelText="否">
          <a href="javascript:void(0)">删除</a>
        </Popconfirm>
      </span>
    ),
  }];

  refeshData = () => {
    const pagination = { ...this.state.pagination };
    pagination.current = pagination.pageNum;
    console.log(pagination);
    this.setState({
      pagination: pagination,
    });
    this.fetch({
      pageSize: pagination.pageSize,
      pageNum: pagination.current,
    });
  }

  state = {
    data: [],
    listtype: [],
    child: [],
    pagination: {},
    loading: false,
    isOpenCreate: false,
    isOpenEdit: false,
  };

  handleTableChange = (pagination, filters, sorter) => {
    const pager = this.state.pagination;
    pager.current = pagination.current != null ? pagination.current : pagination.pageNum;
    this.setState({
      pagination: pager,
    });
    this.fetch({
      pageSize: pagination.pageSize,  //每页现实条数
      pageNum: pagination.current,  //当前页数
      sortField: sorter.field,
      sortOrder: sorter.order,
      type: this.default != '' ? this.default : '',
      ...filters,
    });
  }

  rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      //console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      this.setState({
        delIds: `${selectedRowKeys}`,
      });
    },
    getCheckboxProps: record => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
    }),
  };

  default = '';
  fetch = (params = {}) => {
    this.setState({ loading: true });
    if (params.type != '') {
      this.default = params.type;
    }

    Promise.all([apiAgentType.get('/agentTypePage', {   //分页查询所有
      ...params,
      responseType: 'json'
    }), apiRole.get('/get')]).then(([agentTypesData, rolesData]) => {
      let agentTypes = agentTypesData.data;
      const pagination = agentTypes;
      pagination.total = agentTypes.pages * agentTypes.pageSize;

      rolesData = rolesData.data;
      rolesData.forEach(element => {
        element.key = element.id;
        element.value = element.id;
        element.title = element.name;
      });
      rolesData = jsonToTree({
        json: rolesData,
        keepChild: false
      });

      this.setState({
        loading: false,
        data: agentTypes.list,
        pagination: pagination,
        rolesData: rolesData
      });
    });
  }

  componentDidMount = () => {
    this.fetch({
      pageSize: 20,
      pageNum: 1
    });
  }

  sort = 10;
  type = '';
  startCreate = (type) => {
    if (this.resetFields) this.resetFields();
    this.getMaxSort();
  }

  close = () => {
    this.setState({
      isOpenCreate: false,
      isOpenEdit: false
    });
  }

  startUpdate = (record) => {
    if (this.resetFields) this.resetFields();
    this.setState({
      isOpenEdit: true,
      rowRecord: record,
    });
  }

  handleLogOut = (id) => {
    const { logout } = this.props
    apiAgentType.delete('/deleteAgentType', { id: id }).then((data) => {
      const result = data.data;
      if (result.code == 0) {
        Message.success('删除成功！');
        this.handleTableChange(this.state.pagination, {}, {});
      } else {
        Message.error("删除失败");
      }
    });
  }

  getMaxSort = () => {
    apiAgentType.get('/maxSort').then((data) => {
        if (data != '') {
          this.setState({
            isOpenCreate: true,
            maxSort: parseInt(data.data)+10
          });
        }
      });
  }
  // 接收子组件传入的数据及其方法
  initChildrenParams = (params) => {
    this.resetFields = params.resetFields;
  }

  rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      this.setState({
        delIds: `${selectedRowKeys}`,
      });
    }
  };

  deleteAll = () => {
    const ids = this.state.delIds;
    if (ids == '' || ids == null) {
      Message.error('请选择你要删除的代理商类型！');
      return;
    }
    this.deletesAgentType(ids);
  }

  deletesAgentType = (ids) => {
    apiAgentType.delete('/deletesAgentType', { ids: ids }).then((data) => {
      const result = data.data;
      if (result.code == 0) {
        Message.success('删除成功！');
        this.fetch();
      } else {
        Message.error(result.message);
      }
    });
  }

  render() {
    let _this = this;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };

    class CustomizedForm extends React.Component {
      // 开始搜索
      goSearch = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {   //提交后得到from表单中得值
          if (!err) {
            _this.fetch({ type: values.type, pageSize: 20, pageNum: 1 });
            _this.default = values.type;
          }
        });
        return false;
      }

      render() {
        const { getFieldDecorator } = this.props.form;
        return <Form onSubmit={this.goSearch} layout="inline" style={{ marginBottom: '10px' }}>
          <Popconfirm type="primary" icon="minus" title="您是否要删除选中的所有代理商分类?" onConfirm={_this.deleteAll} okText="是" cancelText="否">
            <Button type="primary" icon="minus" style={{ height: 32, marginRight: 10 }}>删除所选</Button>
          </Popconfirm>
          <FormItem style={{ marginRight: '10px' }}>
            <Button type="primary" icon="plus" onClick={_this.startCreate}>新建代理商类型</Button>
          </FormItem>
        </Form>
      }
    }
    const CusForm = Form.create({})(CustomizedForm);

    return (
      <div>
        <CusForm />
        <PanelBox>
          <Table columns={this.columns}
            rowKey={record => record.id}
            dataSource={this.state.data}
            pagination={this.state.pagination}
            loading={this.state.loading}
            onChange={this.handleTableChange}
            rowSelection={this.rowSelection}
          />
        </PanelBox>
        <Modal
          title="新增代理商类型"
          visible={this.state.isOpenCreate}
          onOk={this.close}
          onCancel={this.close}
          wrapClassName="vertical-center-modal"
          width="800px"
          footer={null}
        >
          <AgentTypeForm close={this.close} refeshData={this.refeshData} maxSort={this.state.maxSort} rolesData={this.state.rolesData} callbackParent={this.initChildrenParams} />
        </Modal>
        <Modal
          title="编辑代理商类型"
          visible={this.state.isOpenEdit}
          onOk={this.close}
          onCancel={this.close}
          wrapClassName="vertical-center-modal"
          width="800px"
          footer={null}
        >
          <AgentTypeForm close={this.close} rowRecord={this.state.rowRecord} refeshData={this.refeshData} rolesData={this.state.rolesData} callbackParent={this.initChildrenParams} />
        </Modal>
      </div>
    );
  }
}
